﻿using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using net_work.Common.Result;

namespace net_work.Middleware;

public class GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
{
    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context); // 调用下一个中间件
        }
        catch (ArgumentException argumentException)
        {
            // 记录异常日志
            logger.LogError(argumentException, "参数异常.");

            // 设置 HTTP 响应
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;

            // 返回统一的错误信息
            var response = AjaxResult.Error($"参数异常：{argumentException.Message}");

            // 写入响应
            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
        catch (InvalidOperationException invalidOperationException)
        {
            // 记录异常日志
            logger.LogError(invalidOperationException, "无效操作异常.");

            // 设置 HTTP 响应
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;

            // 返回统一的错误信息
            var response = AjaxResult.Error($"无效操作：{invalidOperationException.Message}");

            // 写入响应
            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
        catch (DbUpdateException dbUpdateException)
        {
            // 记录异常日志
            logger.LogError(dbUpdateException, "数据库更新异常.");

            // 设置 HTTP 响应
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;

            // 返回统一的错误信息
            var response = AjaxResult.Error($"数据库更新异常：{dbUpdateException.Message}");

            // 写入响应
            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
        catch (Exception ex)
        {
            // 记录异常日志
            logger.LogError(ex, "未处理异常.");

            // 设置 HTTP 响应
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;

            // 返回统一的错误信息
            var response = AjaxResult.Error($"服务异常，请联系管理人员。{ex.Message}");

            // 写入响应
            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
    }
}